from django.db import models
from ..users.models import User

from ..devices.models import Device  # 导入设备模型

class UserDeviceMap(models.Model):
    """
      - user_id 对应 Django 内置的 auth.User id；
      - device_id 对应上面自定义的 Device；
      - permission 是字符串，比如 'read'/'write' 等。
    """
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        db_column='user_id',       # 与数据库字段保持一致
        related_name='device_maps'
    )
    device = models.ForeignKey(
        Device,
        on_delete=models.CASCADE,
        db_column='device_id',
        related_name='user_maps'
    )
    permission = models.CharField(max_length=32)

    class Meta:
        db_table = 'user_device_map'
        unique_together = (('user', 'device'),)   # 保证联合主键唯一

    def __str__(self):
        return f"{self.user.username} - {self.device.device_name} ({self.permission})"
